import datetime
import logging

import pandas as pd
import pytz
from absl import app, flags

from coin.base.param_util import split_string
from coin.base.query_util import query_exchange_rates, query_pta
from coin.support.accounting.logic.constants import COIN_LIST
from coin.support.pta.util.dump_util import dump_pta_to_csv
from coin.tool.strat_monitor.util.display_util import (
    print_strategy_summary, send_strat_summary_to_slack)
from xunkemgmt_client.client.util.query_util import query_trading_summary_snapshots
from xunkemgmt_client.support.pta.util.proto_util import (
    convert_pta_proto_to_df,
    convert_qts_rsp_to_strategy_summary)
from xunkemgmt_client.support.accounting.logic.constants import FIAT_LIST
from xunkemgmt_client.tool.slack_noti import send_to_slack


def main(argv):
  FLAGS = flags.FLAGS
  assert FLAGS.business_unit is not None
  strategy_groups = split_string(FLAGS.strategy_group)
  business_units = split_string(FLAGS.business_unit)
  output_csv_file = FLAGS.output_csv_file
  if FLAGS.trading_date is not None:
    trading_date = datetime.datetime.strptime(FLAGS.trading_date, '%Y%m%d').date()
    rsps = query_pta(start_date=trading_date,
                    end_date=trading_date,
                    business_units=business_units,
                    strategy_groups=strategy_groups,
                    as_proto=True)
    strategy_summary = convert_qts_rsp_to_strategy_summary(rsps)
    dt = datetime.datetime.combine(trading_date, datetime.time.max)
    strategy_summary.fetched_ts = int(dt.replace(tzinfo=pytz.UTC).timestamp() * 10**9)
    base_list = COIN_LIST + FIAT_LIST
    quote = 'USD'
    price_list = query_exchange_rates(base_list, quote, trading_date)
    ticker = {'%s-%s' % (base, quote): price for base, price in zip(base_list, price_list)}
    prefix_msg = ''
    strat_summary_str = print_strategy_summary(
        strategy_summary, mode=FLAGS.mode, ticker=ticker, print_summary=False)
  else:
    strategy_summary = query_trading_summary_snapshots(
        business_units=business_units,
        strategy_groups=strategy_groups,
        as_proto=True)
    prefix_msg = 'PnL snapshot based on snapshot prices\n'
    strat_summary_str = ''
    strat_summary_str += prefix_msg
    strat_summary_str += print_strategy_summary(
        strategy_summary, mode=FLAGS.mode, print_summary=False)

  if len(strategy_summary.summaries) == 0:
    return
  print(strat_summary_str)
  send_strat_summary_to_slack(FLAGS.slack_receiver, strat_summary_str, prefix_msg)
  if output_csv_file is not None:
    pta_df = convert_pta_proto_to_df(strategy_summary)
    pta_df = pta_df[pd.isnull(pta_df['symbol'])]
    dump_pta_to_csv(pta_df, output_csv_file)
    with open(output_csv_file) as f:
      send_to_slack(f.read(), FLAGS.slack_receiver, 'file')


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, 'trading date in form of %Y%m%d.')
  flags.DEFINE_string('strategy_group', None, 'Comma separated strategy_group.')
  flags.DEFINE_string('business_unit', None, 'Comma separated business_unit.')
  flags.DEFINE_string('mode', 'monitor', 'monitor, report')
  flags.DEFINE_string('slack_receiver', None, 'slack recevier')
  flags.DEFINE_string('output_csv_file', None, '')

  logging.basicConfig(
      level='DEBUG',
      format='%(levelname)8s %(asctime)s %(name)s %(filename)s:%(lineno)d] %(message)s')
  app.run(main)
